package com.cloudptt.wp.ui.main;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;

import com.cloudptt.api.product.NetworkListener;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.UpdateUiListener;
import com.cloudptt.api.product.adapter.GCallEventAdapter;
import com.cloudptt.api.product.adapter.ICallInfoDesc;
import com.cloudptt.api.product.func.addr.AddrListener;
import com.cloudptt.api.product.func.message.MsgListener;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.func.sys.listener.SysListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.SysOperator;
import com.cloudptt.api.product.update.UpdateListener;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.BaseActivity;
import com.cloudptt.wp.ui.menu.MenuActivity;
import com.cloudptt.wp.ui.more.SettingActivity;
import com.mcptt.config.local.SysConfig;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity implements SysListener
		, NetworkListener, UpdateListener,MsgListener, ICallInfoDesc, AddrListener, UpdateUiListener {

	public static String THIS_FILE = "MainActivity";
	public final static String KEY_HOME = "MainActivity";
	public final static String KEY_NAME_ISFIRST = "isFirstLogin";
	private TextView id_notify = null;
	public TextView    groupNameTextView = null;
	public Button menuBtn = null;
	public Button settingBtn = null;
	public TextView    callRightTextView = null;
	//	private WakeLock wakeLock;
	private Product product = null;
	private GCallEventAdapter callEventAdapter = null;
	private String lastFloorStr = "";
	private String lastSosStr = "";
	private boolean isShow = false;

	/** permission request 2019/07/15 **/
	private final static int OVERLAY_REQUEST_CODE = 10;
	private static final int PERMISSION_REQUEST_STORAGE = 1;
	private List<String> mPermissionList = new ArrayList<String>();
	private String[] mPermissions = new String[] {
			Manifest.permission.CHANGE_NETWORK_STATE,
			Manifest.permission.INTERNET,
			Manifest.permission.MODIFY_AUDIO_SETTINGS,
			Manifest.permission.READ_PHONE_STATE,
			Manifest.permission.RECEIVE_BOOT_COMPLETED,
			Manifest.permission.WAKE_LOCK,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.BLUETOOTH,
			Manifest.permission.BLUETOOTH_ADMIN,
			Manifest.permission.USE_SIP,
			Manifest.permission.CAMERA,
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.RECORD_AUDIO,
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(THIS_FILE, "On onCreate");
		setContentView(R.layout.activity_main);

		String brand = android.os.Build.BRAND;
		String device = android.os.Build.DEVICE;
		String model = android.os.Build.MODEL;
		Log.d("DeviceInfo", "BRAND = " + brand + " DEVICE = " + device  + " MODEL = " + model);

		groupNameTextView = (TextView) findViewById(R.id.groupNameTextView);
		callRightTextView = (TextView) findViewById(R.id.callRightTextView);
		settingBtn = (Button) findViewById(R.id.rightBtn);
		menuBtn = (Button) findViewById(R.id.leftBtn);
		initView();

		lockScreen();
		ScreenManager.getScreenManager().pushActivity(this);
	}

	@Override
	protected void onResume() {
		Log.i(THIS_FILE, "OnResume");
		super.onResume();
//		checkPermission();
		isShow =  true;

		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		Log.d(THIS_FILE, "onResume 显示屏幕分辨率:\r\n" + displayMetrics.widthPixels + " * " + displayMetrics.heightPixels);

		if(product == null)
		{
			SysApplication app = ((SysApplication)getApplicationContext());
			product = app.getProduct();
		}
		if(product != null) {
			product.setNetworkListener(this);
			product.setSysListener(this);
			product.setMsgListener(this);
			product.setUpdateListener(this);
			product.setAddrListener(this);

//			resetSvrStatueDscp();
		}

		if( product != null)
		{
			if(callEventAdapter == null)
			{
				callEventAdapter = product.getGCallEventAdapter();
			}
			callEventAdapter.setCallInfoDesc(this);
			callEventAdapter.setUpdateUiListener(this);
		}

		updateGroupName();
		resetSvrStatueDscp();
		if (!SysApplication.isFristLogin)
		{
			lastFloorStr = this.getString(R.string.offline_title);
			callRightTextView.setText(lastFloorStr);
		}
		else
		{
//			lastFloorStr = this.getString(R.string.call_desc_idle);
			callRightTextView.setText(lastFloorStr);
		}

//		ignoreBatteryOptimization(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		isShow =  false;
	}

	private void resetSvrStatueDscp() {
//		Log.d(THIS_FILE, "resetSvrStatueDscp lastSosStr = "+lastSosStr);
		if (id_notify != null) {
			if(lastSosStr != null
					&& !lastSosStr.equals(""))
			{
				id_notify.setText(lastSosStr);
//				Log.d(THIS_FILE, "resetSvrStatueDscp lastSosStr = " +lastSosStr);
			}
			else
			{
				SysApplication app = ((SysApplication) getApplicationContext());
				if (product != null) {
					String srvStatusDscp = product.getSrvStatusDscp();
//					Log.d(THIS_FILE, "resetSvrStatueDscp srvStatusDscp = "+srvStatusDscp);
					id_notify.setText(srvStatusDscp);
				}
			}
		}
	}

	public void updateGroupName() {
		Log.i(THIS_FILE, " updateGroupName" );
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			product = app.getProduct();
		}

		if (product != null && product.getCurGroupInfo() != null) {

			String groupName = product.getCurGroupInfo().getName();
			Log.i(THIS_FILE, " updateGroupName groupName = " + groupName);
			groupNameTextView.setText(groupName);
		} else {
			groupNameTextView.setText("");
		}
	}

	@Override
	public void finish() {
		Log.i(THIS_FILE, " finish()");
		super.finish();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		Log.i(THIS_FILE, " onDestroy()");
		super.onDestroy();
	}

	private void initView() {

		Log.i(THIS_FILE, "mainactiviy initView");
		setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);

		id_notify = (TextView) findViewById(R.id.id_notify);

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(THIS_FILE, "onKeyDown keyCode "+ keyCode);

		if (keyCode == KeyEvent.KEYCODE_SOFT_LEFT
				|| keyCode == 66
				|| keyCode == 82
				|| keyCode == 1)
		{
			gotoMenuActivity();
		}
		else if (keyCode == KeyEvent.KEYCODE_BACK
		|| keyCode == 23) {
			gotoSettingActivity();
			if(getFragmentManager().getBackStackEntryCount()>0)
			{
				Log.d(THIS_FILE, "count :"
						+ getFragmentManager().getBackStackEntryCount());
				getFragmentManager().popBackStackImmediate();
			}
			Log.d(THIS_FILE, "onKeyDown end");
			return false;
		}
//		else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
//			if(callEventAdapter != null) {
//				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_UP);
//				return false;
//			}
//		}
//		else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
//			if(callEventAdapter != null) {
//				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_DOWN);
//				return false;
//			}
//		}
//		else if (keyCode == KeyEvent.KEYCODE_MENU) {
//		    super.openOptionsMenu();  // 调用这个，就可以弹出菜单
//		}
		else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ){
			AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			am.adjustStreamVolume( AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_LOWER,
					AudioManager.FLAG_SHOW_UI  );

			return true;
		}else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
			AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			am.adjustStreamVolume( AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_RAISE,
					AudioManager.FLAG_SHOW_UI );
			return true;
		}
//		else if(keyCode == 142){
//			if(callEventAdapter != null)
//			{
//				callEventAdapter.onPtt(Const.MSG_TALK_ON,false);
//			}
//			return true;
//		}
		return super.onKeyDown(keyCode, event);
	}

	public void onHangup(int type){
		Log.d(THIS_FILE, "onHangup type "+ type);
		gotoSettingActivity();
	}
	private void gotoMenuActivity()
	{
		Intent intent = new Intent(MainActivity.this,
				MenuActivity.class);
		startActivity(intent);
		overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
	}

	private void gotoSettingActivity()
	{
		Intent intent = new Intent(MainActivity.this,
				SettingActivity.class);
		startActivity(intent);
		overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		Log.d(THIS_FILE, "onKeyUp keyCode "+ keyCode);
		return super.onKeyUp(keyCode, event);
	}



	@Override
	public void updateCallUser(String callKey, boolean isShow, String userDesc) {
		Log.d(THIS_FILE, "updateCallUser callKey = " + callKey + " isShow = " + isShow + " userDesc = " + userDesc);

//		this.runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
////				callRightTextView.setText(userDesc);
////					findGroupInfoSetDefault();
//			}
//		});

	}

	@Override
	public void updateCallInfoDesc(String callKey, String callNum,String callInfoDesc) {
		Log.d(THIS_FILE, "lightControl updateCallInfoDesc callKey = " + callKey + " callNum = " + callNum + " callInfoDesc = " + callInfoDesc);


		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				showApp();
				lockScreen();
				Log.d(THIS_FILE, "lightControl lockScreen AFTER");
				lastFloorStr = callInfoDesc;
				callRightTextView.setText(lastFloorStr);
//				callRightTextView.setText(callInfoDesc);
				groupNameTextView.setText(callNum);
				Log.d(THIS_FILE, "lightControl lockScreen END");
//					findGroupInfoSetDefault();
			}
		});
//		updateGroupName(gNum);
	}

/*	private void groupNameTextViewUpdate(String callName)
	{
		AddrInfo defaultInfo = product.getDefaultGroupInfo();
		Log.d(THIS_FILE, "groupNameTextViewUpdate callName = " + callName + " defaultInfo = " + defaultInfo);
		String value = "N:"+callName;
		if(defaultInfo.isSameOne(callName)|| defaultInfo.isNameSameOne(callName)) {
			value = "D:"+callName;
		}
//		Log.d(THIS_FILE, "groupNameTextViewUpdate value = " + value);
		groupNameTextView.setText(value);
	}*/
	private void lockScreen() {
		Log.d(THIS_FILE, "lightControl lockScreen");
//		KeyguardManager keyguardManager = (KeyguardManager)mContext.getSystemService(mContext.KEYGUARD_SERVICE);
		PowerManager pm = (PowerManager)MainActivity.this.getSystemService(MainActivity.this.POWER_SERVICE);


		PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.SCREEN_DIM_WAKE_LOCK, "SimpleTimer");
//			mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "SimpleTimer");


		mWakelock.acquire(3000);
		mWakelock.release();
		Log.d(THIS_FILE, "lightControl lockScreen end");
	}

	@Override
	public void updateSecDesc(String callKey, String secStr) {
		Log.d(THIS_FILE, "onSysState secStr = " + secStr);


		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(!secStr.equals("")) {
					String str = getString(R.string.call_desc_14);
					lastFloorStr = str + " " + secStr;
					callRightTextView.setText(lastFloorStr);
//					String str = getString(R.string.call_desc_14);
//					callRightTextView.setText(str + " " + secStr);
				}
			}
		});
	}

	@Override
	public void receiveMsg() {

	}

	@Override
	public void onSysState(SysStateInfo stateInfo) {
		resetSvrStatueDscp();
		Log.d(THIS_FILE, "onSysState stateInfo = " + stateInfo);
		int state = stateInfo.getState();
		int cause = stateInfo.getCause();
		Log.d(THIS_FILE, "onSysState state = " + state);
		if(SysStateInfo.SysState_SvrStartState == state)
		{
			if(SysStateInfo.Cause_Failed == cause
					|| SysStateInfo.Cause_Timeout == cause
					|| SysStateInfo.Cause_Input == cause)
			{
				id_notify.setText(R.string.login_failed);
			}
			SysApplication.isFristLogin = false;
		}
		else if(SysStateInfo.SysState_SipAuthSucState == state)
		{
			if(product == null){
				SysApplication app = ((SysApplication) getApplicationContext());
				this.product = app.getProduct();
			}

			if( product != null)
			{
				Log.d(THIS_FILE,"onSysState makeGroupCall isFristLogin = " + SysApplication.isFristLogin);
				if(!SysApplication.isFristLogin)
				{
					this.product.checkCurVersion(MainActivity.this, false);
					SysApplication.isFristLogin = true;

//					loadAddrList();

					if(callEventAdapter == null)
					{
						callEventAdapter = product.getGCallEventAdapter();
					}
					callEventAdapter.setCallInfoDesc(this);

					Log.d(THIS_FILE,"onSysState makeGroupCall stateInfo = " + stateInfo);
//					callEventAdapter.makeGroupCall();

					String allGNum = product.getSysConfig().getAllCallGNum();
					String sosGNum = "";
					if(product.getSysConfig().getSosGroupInfo() != null) {
						sosGNum = product.getSysConfig().getSosGroupInfo().getGroupNum();
					}
					String curGNum = product.getCurGroupInfo().getMcId();
					String selfNum = product.getSysConfig().getMcpttLoginInfo().getMcIdInfo().getUserId();
					Log.d(THIS_FILE,"initGCallEventAdapter allGNum = " + allGNum + " curGNum = " + curGNum + " selfNum = " + selfNum);
					SysOperator op = (SysOperator)product.getOperator(ProductConst.Func_Sys);
					op.setCallGNum(allGNum,curGNum,sosGNum,selfNum);
				}
			}
		}
		else
		{
			SysApplication.isFristLogin = false;
		}
	}
	@Override
	public void onSipAuthResult(int code)
	{
		Log.d(THIS_FILE, "onSipAuthResult code = " + code);
		if (code/100 != 2)
		{
			lastFloorStr = this.getString(R.string.offline_title);
			callRightTextView.setText(lastFloorStr);
			SysApplication.isFristLogin = false;
//			setIsOnlineIconState(true);
		}
		else {
			lastFloorStr = this.getString(R.string.call_desc_idle);
			callRightTextView.setText(lastFloorStr);
//			setIsOnlineIconState(false);
		}
	}

	@Override
	public void networkChange(boolean isConnect) {
		if(!isConnect)
		{
			lastFloorStr = this.getString(R.string.offline_title);
			callRightTextView.setText(lastFloorStr);
//			callRightTextView.setText(R.string.offline_title);
			SysApplication.isFristLogin = false;
		}
		else{
			//callRightTextView.setText(R.string.call_desc_idle);
		}
		resetSvrStatueDscp();
	}

	public boolean isLogined()
	{
		return true;
	}

	@Override
	public void onForceDetach() {

	}

	@Override
	public void onKeepAlive(boolean isconnected) {

	}

	@Override
	public void onSvrRestart() {

	}

	@Override
	public void onUpdate(int state) {

	}

	public void onAddrUpt()
	{
		Log.d(THIS_FILE, "onAddrUpt");
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
//					updateAddrList();
				updateGroupName();
			}
		});
	}
	public void onOnlineUpt()
	{}

//	private void checkPermission() {
//		if (Build.VERSION.SDK_INT >= 23)
//		{
//			mPermissionList.clear();
//			for (String permission : mPermissions)
//			{
//				if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
//				{
//					mPermissionList.add(permission);
//				}
//			}
//
//			Log.d(THIS_FILE, "mPermissionList = "+mPermissionList);
//			if (!mPermissionList.isEmpty()) {
//				String[] reqpermissions = mPermissionList.toArray(new String[mPermissionList.size()]);
//				requestPermissions(reqpermissions, PERMISSION_REQUEST_STORAGE);
//			} else if(!Settings.canDrawOverlays(getApplicationContext())){
//				startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName())), OVERLAY_REQUEST_CODE);
//			}
//			else{
//			}
//		}
//		((SysApplication) getApplication()).creatProduct();
//	}

	private void showApp(){

		if(!isShow)
		{
			if(product == null){
				SysApplication app = ((SysApplication) getApplicationContext());
				this.product = app.getProduct();
			}
			if( product != null)
			{
				SysConfig config = product.getSysConfig();
				if(!config.isShowApp())
				{
					return;
				}
			}

			if(isAppBackgroud(MainActivity.this)) {
				Log.d(THIS_FILE, "lightControl com.cloudptt.wp.show in");
				Intent ootStartIntent = new Intent(MainActivity.this, MainActivity.class);
				ootStartIntent.addCategory(Intent.CATEGORY_LAUNCHER);
				ootStartIntent.setAction(Intent.ACTION_MAIN);
				ootStartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//			ootStartIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				MainActivity.this.startActivity(ootStartIntent);
			}
		}
	}

	public static boolean isAppBackgroud(Context context) {
		if (context != null) {
			String packName = context.getPackageName();
			List<ActivityManager.RunningTaskInfo> rTasks = getRunningTask(context, 1);
			ActivityManager.RunningTaskInfo task = rTasks.get(0);
			return !packName.equalsIgnoreCase(task.topActivity.getPackageName());
		}
		return false;
	}
	public static List<ActivityManager.RunningTaskInfo> getRunningTask(Context context, int num) {
		if (context != null) {
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			List<ActivityManager.RunningTaskInfo> rTasks = am.getRunningTasks(1);
			return rTasks;
		}
		return null;
	}
	public void UpdateUi(int type,String name)
	{
		Log.d(THIS_FILE, "UpdateUi type = "+type + " name = " +name);
		if(type == UpdateUiListener.Type_State)
		{
			lastSosStr = "";
			resetSvrStatueDscp();
		}
		else if(type == UpdateUiListener.Type_Short)
		{
		}
		else
		{
			if (id_notify != null) {
				String warring_str = this.getString(R.string.sos_warrning);
				if(name != null
						&& !name.equals(""))
				{
					lastSosStr = name +" " + warring_str;
					//Log.d(THIS_FILE, "UpdateUi 1 type = "+type + " lastSosStr = " +lastSosStr);
					id_notify.setText(lastSosStr);
				}
				else
				{
					String self_str = this.getString(R.string.sos_self);
					lastSosStr = self_str +" " + warring_str;
					//Log.d(THIS_FILE, "UpdateUi 2 type = "+type + " lastSosStr = " +lastSosStr);
					id_notify.setText(lastSosStr);
				}
			}
		}
		updateGroupName();
	}

//	private void ignoreBatteryOptimization(Activity activity){
//		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
//		{
//			PowerManager pm = (PowerManager)this.getSystemService(POWER_SERVICE);
//			boolean hasIgnored = pm.isIgnoringBatteryOptimizations(activity.getPackageName());
//			if(!hasIgnored){
//				Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
//				intent.setData(Uri.parse("package:"+activity.getPackageName()));
//				startActivity(intent);
//			}
//		}
//	}
}
